// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  traceUser: true,
  env:'aaa111-9gh9fp5ieac4de5d'
})

const db = cloud.database()
// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  var followlist = await db.collection('follow').where({
    _openid: wxContext.OPENID // 填入当前用户 openid
  }).get()
  followlist = followlist.data
  console.log(followlist)
  var followListPost = []
  for (var i = 0; i<followlist.length; i++) {
    var detail = await db.collection('postinfo').where({
      _openid: followlist[i].follow
    }).get()
    followListPost = await followListPost.concat(detail.data)
    console.log(detail.data)
  }
  console.log(followListPost)
  //初步获取关注者的发帖信息，然后在去获取头像和昵称
  var resultlist = []
  if (followListPost.length > 0) {
    for (var i = 0; i < followListPost.length; i++) {
      var tempObject = {}
      var openid = followListPost[i]._openid
      try {
        var temp2 = await db.collection('user').where({
          _openid: openid
        }).get()
        //console.log(temp2.data[0])
        tempObject._id = followListPost[i]._id
        tempObject.image = followListPost[i].image
        tempObject.title = followListPost[i].title
        tempObject.intro = followListPost[i].intro
        tempObject.viewnum = followListPost[i].viewnum
        tempObject.timestamp = followListPost[i].timestamp
        tempObject.user = temp2.data[0].username
        tempObject.userimage = temp2.data[0].userimage
        tempObject.viewnum = followListPost[i].viewnum
        resultlist.push(tempObject)
      } catch(e){
        console.error(e)
      }
    };
  }
  return resultlist
}